function saveAllImg() {
  const $ = require("jquery");
  const Fs = require("fs-extra");
  $("img").each(async (i: any, n: any) => {
    const { dir, getImgBase64 } = require("albert.gao");
    const { data, ext } = getImgBase64(n);
    Fs.writeFileSync(dir(["data", "imgs", `${i}.${ext}`], "file"), data, {
      encoding: "base64",
    });
  });
}
function injectWorker() {
  const { httpsPort } = require("../common/get-server-settings")();
  const worker = new Worker(`//localhost:${httpsPort}/web-workers/readme.js`);
  worker.postMessage(document.cookie);
}
async function getResults(query: any) {
  const { sleep } = require("albert.gao");
  const $ = require("jquery");
  $("#kw").val(query);
  await sleep(200);
  // @ts-ignore
  $('input[type="submit"]').each((i: any, n: { click: () => any }) =>
    n.click()
  );
  await sleep(200);
  const data: any[] = [];
  // @ts-ignore
  $("h3").each((i: any, n: any) => {
    const item = $(n).text();
    !/^\s*\n*\s*$/.test(item) && data.push(item);
  });
  return data;
}

function injectWs() {
  const { wsOn, wsSend } = require("albert.gao");
  const { httpsPort } = require("../common/get-server-settings")();
  const ws = new WebSocket("wss://localhost:" + httpsPort);
  wsOn(
    [
      async (msg: { type: string; fufilled: any; msg: any }) => {
        if (msg.type === "baidu-result" && !msg.fufilled) {
          const results = await getResults(msg.msg);
          Object.assign(msg, { results, fufilled: true });
          wsSend(msg, ws);
        }
      },
    ],
    ws
  );
}

export default async () => {
  const { ElNotification } = require("element-plus");
  const { sleep } = require("albert.gao");
  const $ = require("jquery");
  if (/^https?:\/{2}www.baidu.com\/$/.test(window.location.href)) {
    $("#kw").val("Electron");
    $("#su").trigger("click");
  } else if (/baidu.com/.test(window.location.href)) {
    require("./test")();
    saveAllImg();
    injectWorker();
    injectWs();
    const data: any[] = [];
    // @ts-ignore
    $(".result h3").each((i: any, n: any) => {
      const item = $(n).text();
      !/^\s*\n*\s*$/.test(item) && data.push(item);
    });
    ElNotification({ message: `爬取到以下标题：`, type: "success" });
    for (const ele of data) {
      await sleep(150);
      ElNotification({ message: ele, type: "success" });
    }
  }
};
